<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;
use app\admin\model\AdminlogModel;

//管理员
class Admin extends Controller
{
    public function getzi(){
        $pid=input('get.pid');
        $list=Db::table('goods_type')->where('pid',$pid)->select();
        echo json_encode($list);
    }
    //管理员登录
    public function login()
    {   
      $admin=Session::get('admin');
      $xitong=Db::table("config")->find(1);
      $this->assign('xitong',$xitong);
      if(Request::instance()->isPost()){
           $code=input('post.captcha');
           $yancode=session('admincaptcha');  //图片验证码
           if($code!=$yancode){
              return ['code'=>0,'msg'=>'验证码有误','data'=>''];
           }
           $name=input('post.username');
           $password=input('post.password');

           $data=Db::table('admin')->where('adminname',$name)->find();
           // print_r(input('post.'));
           // return;
          //  修改上次登录时间
          // 本次登录时间
          // 登录ip地址

           if($data!=null){
                if($data['password']!=md5($password)){//密码错误
                    return ['code'=>0,'msg'=>'密码错误','data'=>''];
                }else{
                    $admin['adminname']=$name;
                    $admin['juese']=$data['juese'];
                    $admin['juese_text']=Db::name('role')->where(['id'=>$data['juese']])->value('name');
                    $admin['id']=$data['id'];
                    $admin['login_time']=date('Y-m-d H:i:s',time());
                    $admin['logintime']=$data['login_time']?date('Y-m-d H:i:s',$data['login_time']):'';
                    $admin['ip']=get_real_ip();
                    Session::set('admin',$admin); //将用户名存入session
                    $data_log['title']='登录';
                    $data_log['save']='登录';
                    $data_log['type_is']=1;
                    $data_log['ip']=get_real_ip();
                    $data_log['createtime']=time();
                    $data_log['a_id']=$admin['id'];
                    $data_log['com']='登录';
                    $AdminlogModel= new AdminlogModel;
                    $AdminlogModel->allowField(true)->save($data_log);

                    $up['login_time']=time();
                    $up['logintime']=$data['login_time'];
                    $up['ip']=get_real_ip();
                    Db::name('admin')->where(['id'=>$data['id']])->update($up);
                    return ['code'=>1,'msg'=>'登录成功','data'=>''];
                }
           }else{//用户不存在
                return ['code'=>0,'msg'=>'用户不存在','data'=>''];
           }
      }
      if(Session::has('admin')){
        return $this->redirect('admin/index/index');
      }else{
        return $this->fetch();
      }
       
    }
    public function do_login()
    {     
        // return 1;
       // $code=input('post.code');
       // $yancode=session('admincaptcha');  //图片验证码
       // if($code!=$yancode){
       //    return 3;
       // }
       $name=input('get.username');
       $password=input('get.password');

       $data=Db::table('admin')->where('adminname',$name)->find();
       // print_r(input('get.'));
       // return;
      //  修改上次登录时间
      // 本次登录时间
      // 登录ip地址

       if($data!=null){
            if($data['password']!=md5($password)){//密码错误
                return 2;
            }else{
                $admin['adminname']=$name;
                $admin['juese']=$data['juese'];
                $admin['juese_text']=Db::name('role')->where(['id'=>$data['juese']])->value('name');
                $admin['id']=$data['id'];
                $admin['login_time']=date('Y-m-d H:i:s',time());
                $admin['logintime']=$data['login_time']?date('Y-m-d H:i:s',$data['login_time']):'';
                $admin['ip']=get_real_ip();
                Session::set('admin',$admin); //将用户名存入session
                $data_log['title']='登录';
                $data_log['save']='登录';
                $data_log['type_is']=1;
                $data_log['ip']=get_real_ip();
                $data_log['createtime']=time();
                $data_log['a_id']=$admin['id'];
                $data_log['com']='登录';
                $AdminlogModel= new AdminlogModel;
                $AdminlogModel->allowField(true)->save($data_log);

                $up['login_time']=time();
                $up['logintime']=$data['login_time'];
                $up['ip']=get_real_ip();
                Db::name('admin')->where(['id'=>$data['id']])->update($up);
                return 0;
            }
       }else{//用户不存在
            return 1;
       }
       
       // return $this->fetch();
       
    }
    //退出登录
    public function loginout()
    {   
      $data_log['title']='退出登录';
      $data_log['save']='退出登录';
      $data_log['type_is']=1;
      $data_log['ip']=get_real_ip();
      $data_log['createtime']=time();
      $admin=Session::get('admin');
      $data_log['a_id']=$admin['id'];
      $data_log['com']='退出登录';
      $AdminlogModel= new AdminlogModel;
      $AdminlogModel->allowField(true)->save($data_log);
       Session::delete('admin');  //删除session
       return $this->redirect('admin/admin/login');
    }
    //忘记密码页面
    public function forget()
    {   

       return $this->fetch();
    }
    //找回密码
    public function findpass()
    {     
       $data=[];
       $phone=input("get.phone");
       $num=Db::table("admin")->where("phone",$phone)->find();
       if(empty($num)){
          return 3;
       }
       $code=input("get.code");  //图片验证码
       $yancode=session('admincaptcha');  //图片验证码
       if($code!=$yancode){
          return 2;
       }
       $vercode=input("get.vercode");  //输入的短信验证码
       $yan=$this->yan($phone);
       $code=session("adminyan");  //发送的短信验证码
       if($vercode!=$yan){
       // if($vercode!="111"){
          return 1;
       }else{
        $data_log['title']='找回密码';
        $data_log['save']='找回密码';
        $data_log['type_is']=1;
        $data_log['ip']=get_real_ip();
        $data_log['createtime']=time();
        $admin=Session::get('admin');
        $data_log['a_id']=$admin['id'];
        $data_log['com']='找回密码';
        $AdminlogModel= new AdminlogModel;
        $AdminlogModel->allowField(true)->save($data_log);
        Session::set('phone',$phone);
          return 0;
       }
    }
    //短信验证
    public function yan(){
     $code="";
        for ($i=0; $i <6 ; $i++) { 
            $code.=rand(0,9);
        }
        $phone=input("post.phone");
        $da=$this->duanxin($phone,$code);
        session("adminyan",$code);
        return $da['code']; 

      return 200;
    }
    public function duanxin($phone,$code){
        $host = "https://smssend.shumaidata.com";
        $path = "/sms/send";
        $method = "POST";
        $appcode = "a34d897c5e5840db8b107e02bdc88aaa";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "receive=$phone&tag=".urlencode($code)."&templateId=M09DD535F4";
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //设定返回信息中是否包含响应信息头，启用时会将头文件的信息作为数据流输出，true 表示输出信息头, false表示不输出信息头
        //如果需要将字符串转成json，请将 CURLOPT_HEADER 设置成 false
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        // var_dump(curl_exec($curl));
        return json_decode(curl_exec($curl),true);
    }
    //重置密码
    public function repass()
    {   
      $phone=Session::pull('phone');
      $password=input("get.password");
        $num=Db::table("admin")->where("phone",$phone)->update(['password' => md5($password)]);
        if($num>0){
        $data_log['title']='重置密码';
        $data_log['save']='重置密码';
        $data_log['type_is']=1;
        $data_log['ip']=get_real_ip();
        $data_log['createtime']=time();
        $admin=Session::get('admin');
        $data_log['a_id']=$admin['id'];
        $data_log['com']='重置密码';
        $AdminlogModel= new AdminlogModel;
        $AdminlogModel->allowField(true)->save($data_log);
            return 1;  //修改成功
        }else{
            return 0;  //修改失败
        }
    }
    //修改密码页面
    public function password()
    {   
       return $this->fetch();
    }
    public function update_pass()
    {   

       $session=Session::get("admin");
       $oldpass=input("post.oldPassword");
       $newpass=input("post.password");
       $repass=input("post.repassword");
       $data=Db::table('admin')->where('adminname',$session['adminname'])->find();
       if($data['password'] != md5($oldpass)){ //当前密码不正确
            return 0;
       }elseif(md5($newpass)==md5($oldpass)){ //新旧密码一样
            return 1;
       }elseif(md5($newpass)!=md5($repass)){  //两次密码不一致
            return 2;
       }else{
            $num=Db::table("admin")->where("adminname",$session['adminname'])->update(['password' => md5($newpass)]);
            if($num>0){
            $data_log['title']='修改密码';
            $data_log['save']='修改密码';
            $data_log['type_is']=1;
            $data_log['ip']=get_real_ip();
            $data_log['createtime']=time();
            $admin=Session::get('admin');
            $data_log['a_id']=$admin['id'];
            $data_log['com']='修改密码';
            $AdminlogModel= new AdminlogModel;
            $AdminlogModel->allowField(true)->save($data_log);
                Session::delete('admin');  //删除session
                return 3;
            }else{
                return 4;
            }
       }
    }
    //管理员列表显示
    public function list1()
    {   
        if(!Session::has('admin')){
            return $this->redirect('admin/admin/login');   //跳转到移动端
        }
       return $this->fetch();
    }
    public function lst()
    {   
        $req=input("post.");
        $page=$req['page'];  //当前页   1
        $limit=$req['limit']; //每页几行数据  10
        $begin=($page-1)*10;   //0,10  10,10 
        $where=[];
        if(isset($req['adminname']) && $req['adminname']){
            $where['adminname']=['like','%'.$req['adminname'].'%'];
        }
        $count=Db::table('admin')->where($where)->count();
        $data=[];
        // $list=Db::table('business')->select();
        $list=Db::table('admin')->limit($begin,$limit)->where($where)->order("id desc")->select();
        for ($i=0; $i <count($list) ; $i++) { 
          $list[$i]['addtime']=date("Y-m-d",$list[$i]['addtime']);
          $juese=Db::table('role')->find($list[$i]['juese']);
          $list[$i]['juese']=$juese['name'];
          
          
        }
        $data['code']=0;
        $data['data']=$list;
        $data['msg']="返回成功";
        $data['count']=$count;
        echo json_encode($data);

    }
    //管理员添加/修改页
    public function userform()
    {   
       $admin=Session::get('admin');
       $this->assign('admin',$admin);
       // dump($admin);
       $adminrole=$admin['juese'];
       if($adminrole==1){   //超管
            $role=Db::table('role')->where('id','<>',1)->select();
            $this->assign('rolelist',$role);
       }elseif($adminrole==2){   //普管
            $role=Db::table('role')->where('id','not in',[1,2])->select();
            $this->assign('rolelist',$role);
       }
      
       $cao=input("get.do");
       if($cao=="update"){
            $id=input("get.id");   //id存在,表示修改
            $data=Db::table('admin')->where('id',$id)->find();
         
            $this->assign("data",$data);
       }
       $this->assign("do",$cao);
       return $this->fetch();
    }
    //文件上传
    public function upload(){
        $return=[];
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('image');
            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'admin');
                if($info){
                    // 成功上传后 获取上传信息
                    $return['code']=0;
                    $return['msg']="上传成功";
                    $return['data']=$info->getSaveName();
                }else{
                    // 上传失败获取错误信息
                    $return['code']=1;
                    // $return['msg']="上传成功";
                    $return['msg']="上传失败";
                    $return['data']=$file->getError();
                }
            }
        return json_encode($return);
    }
     public function pass(){
        $admin=Session::get('admin');
       $this->assign('admin',$admin);
       return $this->fetch();
    }
    public function add(){
        $admin=Session::get('admin');
        $this->assign('admin',$admin);
        $adminrole=$admin['juese'];
        if($adminrole==1){   //超管
            $role=Db::table('role')->where('id','<>',1)->select();
            $this->assign('rolelist',$role);
        }else{
            $this->assign('rolelist',[]);
        }
       
        return $this->fetch();
    }
    //执行添加
    public function do_add()
    {   
      $req=input("post.");
      $pass=$req['password'];
      $repass=$req['repass'];
      if($pass!=$repass){
        return 4;
      }
        $data['adminname']=$req['adminname'];
        if(isset($req['juese'])&& !empty($req['juese'])){
            $data['juese']=$req['juese'];
        }
        // if($req['juese']==3 && $req['region']==''){
     //        return 5;
     //    }
        $admin=Db::table('admin')->where('adminname', $data['adminname'])->count();
        if($admin>0){
            return 2;  //该管理员已存在
        }
        $data['password']=md5($req['password']);
      $data['addtime']=time();
      if(!empty($req['name'])){
        $data['name']=$req['name'];
      }
      if(!empty($req['phone'])){
        $data['phone']=$req['phone'];
      }
      
  
        $num=Db::table('admin')->insert($data);
        if($num>0){ //添加成功
        $data_log['title']='添加管理员';
        $data_log['save']='添加管理员';
        $data_log['type_is']=1;
        $data_log['ip']=get_real_ip();
        $data_log['createtime']=time();
        $admin=Session::get('admin');
        $data_log['a_id']=$admin['id'];
        $data_log['com']=json_encode($req,320);
        $AdminlogModel= new AdminlogModel;
        $AdminlogModel->allowField(true)->save($data_log);
            return 1;
        }else{
            
            return 0;
        }

    }
    public function update(){
        $admin=Session::get('admin');
        $this->assign('admin',$admin);
        $adminrole=$admin['juese'];
        if($adminrole==1){   //超管
            $role=Db::table('role')->where('id','<>',1)->select();
            $this->assign('rolelist',$role);
        }else{
            $role=Db::table('role')->where('id','<>',1)->select();
            $this->assign('rolelist',$role);
        }
        $id=input("get.id");   //id存在,表示修改
        $data=Db::table('admin')->where('id',$id)->find();
        $this->assign("data",$data);
        
       return $this->fetch();
    }
    //执行修改
    public function do_update()
    {   
        $id=input("get.id");
        $req=input("post.");
        if(!empty($req['adminname'])){
             $data['adminname']=$req['adminname'];
             $da=Db::table("admin")->where("adminname",$data['adminname'])->where("id","<>",$id)->find();
             if(!empty($da)){
                return 3;
             }
        }
        $num=Db::table('admin')->where('id', $id)->update($req);
        if($num>0){
        $data_log['title']='修改管理员';
        $data_log['save']='修改管理员';
        $data_log['type_is']=1;
        $data_log['ip']=get_real_ip();
        $data_log['createtime']=time();
        $admin=Session::get('admin');
        $data_log['a_id']=$admin['id'];
        $data_log['com']=json_encode($req,320);
        $AdminlogModel= new AdminlogModel;
        $AdminlogModel->allowField(true)->save($data_log);
            return 1;
        }else{
            return 0;
        }
    }
    //执行删除
    public function do_del()
    {   
        $data=input("post.");
        $admin=Db::table('admin')->where('id',"in",$data['id'])->select();
        $adminname=Db::table('admin')->where('id',"in",$data['id'])->column('adminname');

        $num=Db::table("admin")->where("id","in",$data['id'])->delete();
        // return json_encode($data['id']);  
      if($num>0){
        $data_log['title']='删除管理员';
        $data_log['save']='删除管理员';
        $data_log['type_is']=1;
        $data_log['ip']=get_real_ip();
        $data_log['createtime']=time();
        $admin=Session::get('admin');
        $data_log['a_id']=$admin['id'];
        $data_log['com']=implode(',',$adminname);
        $AdminlogModel= new AdminlogModel;
        $AdminlogModel->allowField(true)->save($data_log);
        for ($i=0; $i <count($admin) ; $i++) { 
            if(!empty($admin[$i]['img'])){
            $path="uploads/admin/".$admin[$i]['img'];
            //删除之前图片
            if(file_exists($path)){
              unlink($path);
            }
          }
        }
      }
      return $num;  
    }
    //修改账号密码
    //执行修改
    //执行搜索
    public function search()
    {   
        if(!Session::has('admin')){
            return $this->redirect('admin/admin/login');   //跳转到移动端
        }
        $page=input("post.page");  //当前页   1
        $limit=input("post.limit"); //每页几行数据  10
        $begin=($page-1)*$limit;   //0,10  10,10 

        // $adminname=input("post.username");
        $req=input('post.'); 
        $where=[];
        if(isset($req['username']) && !empty($req['username'])) {  //统计里get传参
          $where['adminname']=['like','%'.$req['username'].'%'];
        }
    
        $data=[];
        // dump($where);
        $list=Db::table('admin')->limit($begin,$limit)->where($where)->order("id desc")->select();
        // if($adminname != ""){
        //  $list=Db::table('admin')->where('adminname',"like","%".$adminname."%")->limit($begin,$limit)->order("id desc")->select();
        // }else{
        //  $list=Db::table('admin')->limit($begin,$limit)->order("id desc")->select();
        // }
       for ($i=0; $i <count($list) ; $i++) { 
          $list[$i]['addtime']=date("Y-m-d",$list[$i]['addtime']);
          $juese=Db::table('role')->find($list[$i]['juese']);
          $list[$i]['juese']=$juese['name'];
      
        }
        $data['code']=0;
        $data['data']=$list;
        $data['msg']="返回成功";
        $data['count']=count($list);
        echo json_encode($data);
    }
    public function yan1()
    { 
      
      //1.创建黑色画布
        $image = imagecreatetruecolor(100, 30);
         
        //2.为画布定义(背景)颜色
        $bgcolor = imagecolorallocate($image, 255, 255, 255);
         
        //3.填充颜色
        imagefill($image, 0, 0, $bgcolor);
         
        // 4.设置验证码内容
         
        //4.1 定义验证码的内容
        $content = "0123456789";
         
        //4.1 创建一个变量存储产生的验证码数据，便于用户提交核对
        $captcha = "";
        for ($i = 0; $i < 4; $i++) {
            // 字体大小
            $fontsize = 100;
            // 字体颜色
            $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
            // 设置字体内容
            $fontcontent = substr($content, mt_rand(0, strlen($content)), 1);
            $captcha .= $fontcontent;
            // 显示的坐标
            $x = ($i * 100 / 4) + mt_rand(5, 10);
            $y = mt_rand(5, 10);
            // 填充内容到画布中
            imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
        }
        // $_SESSION["captcha"] = $captcha;
         session("admincaptcha",$captcha);
        //4.3 设置背景干扰元素
        for ($$i = 0; $i < 200; $i++) {
            $pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
            imagesetpixel($image, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
        }
         
        //4.4 设置干扰线
        for ($i = 0; $i < 3; $i++) {
            $linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
            imageline($image, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $linecolor);
        }
         
        //5.向浏览器输出图片头信息
        header('content-type:image/png');
         
        //6.输出图片到浏览器
        imagepng($image);
         
        //7.销毁图片
        imagedestroy($image);
    }
    public function xiu_pass(){
      $id=input("get.id");
      $password=input("post.password");
      $repass=input("post.repass");
      if($password!=$repass){
        return 3;
      }
      $num=Db::table("admin")->where('id',$id)->update(['password'=>md5($password)]);
      return $num;
    }

}